/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2023-04-17
 * Time:22:28
 */

/**
 * BM7链表中环的入口结点
 */

public class EntryNodeOfLoop {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        head.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node2; // 构造一个环形链表，入口节点为 2

        Solution solution = new Solution();
        ListNode entry = EntryNodeOfLoop(head);
        if (entry != null) {
            System.out.println(entry.val); // 输出 2
        } else {
            System.out.println("null");
        }

    }
    public static ListNode EntryNodeOfLoop(ListNode pHead) {
        if (pHead == null || pHead.next == null) {
            return null;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = pHead;
        ListNode cur = dummy;
        ListNode pre = dummy;
        while (pre != null && pre.next != null) {
            cur = cur.next;
            pre = pre.next.next;
            if (cur == pre) {
                ListNode ptr = dummy;
                while (ptr != cur) {
                    ptr = ptr.next;
                    cur = cur.next;
                }
                return ptr;
            }
        }
        return null;
    }
}
